"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _react = _interopRequireDefault(require("react"));
var _reactDom = _interopRequireDefault(require("react-dom"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _tweenFunctions = _interopRequireDefault(require("tween-functions"));
var _rcTweenOne = require("rc-tween-one");
var _ticker = _interopRequireDefault(require("rc-tween-one/lib/ticker"));
var _EventDispatcher = _interopRequireDefault(require("./EventDispatcher"));
var _util = require("./util");
var _excluded = ["animation", "always", "component", "location", "targetId", "componentProps"];
function _interopRequireDefault(e) { return e && e.__esModule ? e : { "default": e }; }
function _objectWithoutProperties(e, t) { if (null == e) return {}; var o, r, i = _objectWithoutPropertiesLoose(e, t); if (Object.getOwnPropertySymbols) { var s = Object.getOwnPropertySymbols(e); for (r = 0; r < s.length; r++) o = s[r], t.includes(o) || {}.propertyIsEnumerable.call(e, o) && (i[o] = e[o]); } return i; }
function _objectWithoutPropertiesLoose(r, e) { if (null == r) return {}; var t = {}; for (var n in r) if ({}.hasOwnProperty.call(r, n)) { if (e.includes(n)) continue; t[n] = r[n]; } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? Object(arguments[r]) : {}, o = Object.keys(t); "function" == typeof Object.getOwnPropertySymbols && o.push.apply(o, Object.getOwnPropertySymbols(t).filter(function (e) { return Object.getOwnPropertyDescriptor(t, e).enumerable; })), o.forEach(function (r) { _defineProperty(e, r, t[r]); }); } return e; }
function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
function _possibleConstructorReturn(t, e) { if (e && ("object" == typeof e || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
var tickerId = 0;
function playScaleToArray(playScale) {
  if (Array.isArray(playScale)) {
    if (playScale.length === 2) {
      return playScale;
    }
    return [playScale[0] || 0, playScale[1] || 1];
  } else if (playScale) {
    return [playScale, 1];
  }
  return [0, 1];
}
var ScrollParallax = /*#__PURE__*/function (_React$Component) {
  function ScrollParallax(props) {
    var _this;
    _classCallCheck(this, ScrollParallax);
    _this = _callSuper(this, ScrollParallax, [props]);
    _defineProperty(_this, "setDefaultData", function (_vars) {
      var vars = (0, _util.dataToArray)(_vars);
      var varsForIn = function varsForIn(item, i) {
        var playScale = playScaleToArray(item.playScale).map(function (data) {
          return data * _this.clientHeight;
        });
        var aItem = _objectSpread({}, item);
        delete aItem.playScale;
        var cItem = _objectSpread({}, item);
        delete cItem.playScale;
        cItem.delay = playScale[0];
        aItem.delay = playScale[0];
        cItem.duration = playScale[1] - playScale[0];
        aItem.duration = playScale[1] - playScale[0];
        cItem.onStart = null;
        cItem.onUpdate = null;
        cItem.onComplete = null;
        cItem.onRepeat = null;
        aItem.onStart = aItem.onStart || _util.noop;
        aItem.onComplete = aItem.onComplete || _util.noop;
        aItem.onUpdate = aItem.onUpdate || _util.noop;
        aItem.onStartBack = aItem.onStartBack || _util.noop;
        aItem.onCompleteBack = aItem.onCompleteBack || _util.noop;
        _this.defaultTweenData[i] = cItem;
        _this.defaultData[i] = aItem;
      };
      vars.forEach(varsForIn);
    });
    _defineProperty(_this, "resizeEventListener", function () {
      if (_this.defaultData[_this.defaultData.length - 1] && _this.defaultData[_this.defaultData.length - 1].onCompleteBool && !_this.props.always) {
        return;
      }
      _this.scrollTop = (0, _util.currentScrollTop)();
      _this.target = _this.props.targetId && document.getElementById(_this.props.targetId);
      _this.clientHeight = _this.target ? _this.target.clientHeight : (0, _util.windowHeight)();
      _this.setDefaultData(_this.props.animation || {});
      if (_this.timeline) {
        _this.timeline.resetDefaultStyle();
      }
      _this.timeline = new _rcTweenOne.Tween(_this.dom, _this.defaultTweenData);
      _this.timeline.init();
      _this.scrollEventListener();
    });
    _defineProperty(_this, "scrollEventListener", function () {
      var scrollTop = _this.target ? _this.target.scrollTop : (0, _util.currentScrollTop)();
      _this.clientHeight = _this.target ? _this.target.clientHeight : (0, _util.windowHeight)();
      var dom = _this.props.location ? document.getElementById(_this.props.location) : _this.dom;
      if (!dom) {
        throw new Error('"location" is null');
      }
      var targetTop = _this.target ? _this.target.getBoundingClientRect().top : 0;
      var offsetTop = dom.getBoundingClientRect().top + scrollTop - targetTop;
      var elementShowHeight = scrollTop - offsetTop + _this.clientHeight;
      var currentShow = _this.scrollTop - offsetTop + _this.clientHeight;
      _this.defaultData.forEach(function (item, i) {
        var duration = _this.defaultData.map(function (c, ii) {
          return ii < i && c.delay + c.duration || 0;
        }).reduce(function (a, b) {
          return a + b;
        });
        var noUpdate;
        if (elementShowHeight <= item.delay + duration) {
          if (!item.onCompleteBackBool && item.onStartBool) {
            item.onCompleteBackBool = true;
            noUpdate = true;
            item.onCompleteBack();
          }
        } else {
          item.onCompleteBackBool = false;
        }
        if (elementShowHeight >= item.delay + duration) {
          if (!item.onStartBool) {
            item.onStartBool = true;
            noUpdate = true;
            item.onStart();
          }
        } else {
          item.onStartBool = false;
        }
        if (elementShowHeight <= item.delay + item.duration + duration) {
          if (!item.onStartBackBool && item.onCompleteBool) {
            item.onStartBackBool = true;
            noUpdate = true;
            item.onStartBack();
          }
        } else {
          item.onStartBackBool = false;
        }
        if (elementShowHeight >= item.delay + item.duration + duration) {
          if (!item.onCompleteBool) {
            item.onCompleteBool = true;
            noUpdate = true;
            item.onComplete();
          }
        } else {
          item.onCompleteBool = false;
        }
        if (elementShowHeight >= item.delay + duration && elementShowHeight <= item.delay + item.duration + duration && !noUpdate) {
          item.onUpdate(elementShowHeight / (item.delay + item.duration + duration));
        }
      });
      _ticker["default"].clear(_this.tickerId);
      _this.tickerId = "scrollParallax".concat(Date.now(), "-").concat(tickerId);
      tickerId++;
      if (tickerId >= Number.MAX_VALUE) {
        tickerId = 0;
      }
      var startFrame = _ticker["default"].frame;
      _ticker["default"].wake(_this.tickerId, function () {
        var moment = (_ticker["default"].frame - startFrame) * _ticker["default"].perFrame;
        var ratio = _tweenFunctions["default"].easeOutQuad(moment, 0.08, 1, 300);
        _this.timeline.frame(currentShow + ratio * (elementShowHeight - currentShow));
        if (moment >= 300) {
          _ticker["default"].clear(_this.tickerId);
        }
      });
      _this.scrollTop = scrollTop;
      // 如果不一直靠滚动来执行动画，always=false而且动画全执行完了，，删除scrollEvent;
      if (_this.defaultData[_this.defaultData.length - 1].onCompleteBool && _this.eventType && !_this.props.always) {
        _EventDispatcher["default"].removeEventListener(_this.eventType, _this.scrollEventListener, _this.target);
      }
    });
    _this.scrollTop = 0;
    _this.defaultTweenData = [];
    _this.defaultData = [];
    _this.state = {
      $self: _this
    };
    return _this;
  }
  _inherits(ScrollParallax, _React$Component);
  return _createClass(ScrollParallax, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.dom = _reactDom["default"].findDOMNode(this);
      var date = Date.now();
      var length = _EventDispatcher["default"]._listeners.scroll ? _EventDispatcher["default"]._listeners.scroll.length : 0;
      this.eventType = "scroll.scrollEvent".concat(date).concat(length);
      this.eventResize = "resize.resizeEvent".concat(date).concat(length);
      this.resizeEventListener();
      _EventDispatcher["default"].addEventListener(this.eventResize, this.resizeEventListener, this.target);
      // 预注册;
      this.timeline.frame(0);
      this.scrollEventListener();
      _EventDispatcher["default"].addEventListener(this.eventType, this.scrollEventListener, this.target);
    }
  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      _EventDispatcher["default"].removeEventListener(this.eventType, this.scrollEventListener, this.target);
      _EventDispatcher["default"].removeEventListener(this.eventResize, this.resizeEventListener, this.target);
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props = this.props,
        animation = _this$props.animation,
        always = _this$props.always,
        component = _this$props.component,
        location = _this$props.location,
        targetId = _this$props.targetId,
        componentProps = _this$props.componentProps,
        props = _objectWithoutProperties(_this$props, _excluded);
      var style = _objectSpread({}, props.style);
      Object.keys(style).forEach(function (p) {
        if (p.indexOf('filter') >= 0 || p.indexOf('Filter') >= 0) {
          // ['Webkit', 'Moz', 'Ms', 'ms'].forEach(prefix=> style[`${prefix}Filter`] = style[p]);
          var transformArr = ['Webkit', 'Moz', 'Ms', 'ms'];
          for (var i = 0; i < transformArr.length; i++) {
            style["".concat(transformArr[i], "Filter")] = style[p];
          }
        }
      });
      props.style = style;
      return /*#__PURE__*/_react["default"].createElement(this.props.component, _objectSpread({}, props, componentProps));
    }
  }], [{
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, _ref) {
      var prevProps = _ref.prevProps,
        $self = _ref.$self;
      var nextState = {
        prevProps: props
      };
      if (prevProps && props !== prevProps) {
        var equal = (0, _util.objectEqual)(prevProps.animation, props.animation);
        if (!equal) {
          $self.setDefaultData(props.animation || {});
          $self.timeline.resetAnimData();
          $self.timeline.setDefaultData($self.defaultTweenData);
        }
      }
      return nextState; // eslint-disable-line
    }
  }]);
}(_react["default"].Component);
_defineProperty(ScrollParallax, "propTypes", {
  component: _propTypes["default"].any,
  animation: _propTypes["default"].any,
  always: _propTypes["default"].bool,
  location: _propTypes["default"].string,
  children: _propTypes["default"].any,
  className: _propTypes["default"].string,
  style: _propTypes["default"].any,
  id: _propTypes["default"].string,
  targetId: _propTypes["default"].string,
  componentProps: _propTypes["default"].object
});
_defineProperty(ScrollParallax, "defaultProps", {
  component: 'div',
  always: true,
  componentProps: {}
});
ScrollParallax.isScrollParallax = true;
var _default = exports["default"] = ScrollParallax;